package kmhc.handler;

import java.util.Optional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.HandleBeforeSave;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.security.crypto.password.PasswordEncoder;

import kmhc.domain.user.User;
import kmhc.repository.user.UserRepository;

@RepositoryEventHandler(User.class)
public class UserEventHandler {

	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Autowired
	private UserRepository userRepo;
	
	@PersistenceContext
	private EntityManager entityManager;
	
	@HandleBeforeSave
	public void handleUserBeforeSave(User user) {
		// If you don't read this, it's going to be an object in the cache
		entityManager.detach(user);
		// try get the original user
		Optional<User> optional = userRepo.findByUsername(user.getUsername());
		if (optional.isPresent()) {
			// compare password change
			User origin = optional.get();
			if (!origin.getPassword().equals(user.getPassword())) {
				user.setPassword(passwordEncoder.encode(user.getPassword()));
			}
		}
	}
	
	@HandleBeforeCreate
	public void handleUserBeforeCreate(User user) {
		user.setPassword(passwordEncoder.encode(user.getPassword()));
	}
}
